package com.fzb.fetch.mail;

import com.fzb.common.IOUtil;
import flexjson.JSONDeserializer;
import org.apache.log4j.Logger;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.net.URLEncoder;
import java.util.*;

public class SinaEmail {

    private static Logger LOGGER = Logger.getLogger(SinaEmail.class);
    private static ScriptEngine engine;

    static {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        engine = engineManager.getEngineByName("nashorn");
        try {
            engine.eval(IOUtil.getStringInputStream(HttpUtil.class.getResourceAsStream("/osslogin.js")));
        } catch (ScriptException e) {
            LOGGER.error("load sina login.js error", e);
        }
    }

    public static void fetch(String userName, String pwd) throws Exception {

        long serverTime = System.currentTimeMillis() / 1000L;
        int nonce = new Random(100000L).nextInt() + 100000;

        String password = engine.eval("password('" + serverTime + "','" + nonce + "','" + pwd + "')").toString();
        String su = URLEncoder.encode(new String(Base64.getEncoder().encode(URLEncoder.encode(userName, "UTF-8").getBytes())), "UTF-8");
        String url = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_=" + serverTime;
        String str = "entry=cnmail&gateway=1&savestate=30&useticket=0&su=" + su + "&service=sso&servertime=" + serverTime + "&nonce=" + nonce + "&pwencode=rsa2&rsakv=1330428213&sp=" + password + "&encoding=UTF-8&cdult=3&domain=sina.com.cn&prelt=562&returntype=TEXT";
        ResponseData<String> t = new ResponseData<String>() {
        };
        HttpUtil.postContentType(url, str.getBytes(), t, null);
        Map json = (Map) new JSONDeserializer().deserialize(t.getT());
        List<String> urls = (List) json.get("crossDomainUrlList");
        urls.add("http://mail.sina.com.cn/cgi-bin/sla.php?vt=0");
        for (String accessUrl : urls) {
            accessUrl = accessUrl + "&callback=sinaSSOController.doCrossDomainCallBack&scriptId=ssoscript2&client=ssologin.js(v1.4.18)&_=1444529802162";
            if (!accessUrl.contains("passport.weibo.cn")) {
                HttpUtil.getContentType(accessUrl, t, null);
            }
        }
        HttpUtil.postContentType("http://m1.mail.sina.com.cn/wa.php?a=list_mail", "fid=new&order=htime&sorttype=desc&type=0&pageno=1&tag=-1&webmail=1".getBytes(), t, null);
        Map ssJson = (Map) new JSONDeserializer().deserialize(t.getT());
        Long count = (Long) ((HashMap) ((Map) ssJson.get("data")).get("total")).get("count");
        LOGGER.info(ssJson);
        LOGGER.info("email count" + count);
    }

    public static void main(String[] args)
            throws Exception {
        fetch("wozcc94@sina.cn", "hahahahah");
    }
}
